<?php

namespace App\V3\V3_2_7\Controllers;

use App\Helper\Utils\Util;
use App\V3\V3_2_7\Models\MaterielProductContentModel;
use App\V3\V3_2_7\Models\MaterielsTypeModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use App\V3\V3_2_7\Models\MaterielClassModel;
use Illuminate\Support\Facades\Validator;
use App\V3\V3_2_7\Services\MaterielClassService;

class MaterielClassController extends BaseController
{
    public function list(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        return $this->success(MaterielClassService::index($this->getMainUserId(), $data));
    }

    /**
     *物料分类下拉列表
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/5 14:22
     * @return \Illuminate\Http\JsonResponse
     */
    public function select(Request $request)
    {
//        $validator = Validator::make($data = $request->all(), [
//            //type:0->一级分类;1->二级分类
//            'is_product_class' => [
//                'required',
//                Rule::In([0, 1]),
//            ],//是否为成品库分类;0:否;1:是;
//        ],
//            [
//                'is_product_class.required' => '参数`商品分类类型`缺失',
//                'is_product_class.in' => '参数`商品分类类型`异常不合法，请重新选择',
//            ]);
//
//        //参数错误响应
//        if ($info = $validator->errors()->first()) {
//            return $this->fail('', $info);
//        }

        return $this->success(
            MaterielClassService::select($this->getMainUserId(), $request->is_product_class)
        );
    }

    /**
     * 新建物料商品分类
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/5 15:15
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            //type:0->一级分类;1->二级分类
            'type' => [
                'required',
                Rule::In([0, 1, 2]),
            ],//页面大小
            'class_name' => 'required',//分类名称
            /* 'class_no' => 'required',//分类编号 */
            'parent_id' => 'required|integer',//上级分类id
        ],
            [
                'type.required' => '请选择类型',
                'type.in' => '类型不合法，请重新选择',
                'class_name.required' => '请输入分类名称',
                /* 'class_no.required' => '请输入分类编号', */
//                'class_no.size' => '编号只能由四位的字母或数字组成',
                'parent_id.required' => '请选择上一级分类',
                'parent_id.integer' => '请输入分类编号',
            ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['parent_id'] = !$data['type'] ? 0 : $data['parent_id'];
        $data['created_at'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['is_product_class'] = empty($data['is_product_class']) ? 0 : 1;

        $result = MaterielClassService::add($this->getMainUserId(), $data);

        if (!$result['code']) {
            $logData = '分类名称：' . $data['class_name'] . ' 创建成功！';
            $this->log('新建商品分类', $data, $logData);
            return $this->success(['id' => $result['data']]);
        } else {
            return $this->fail('', $result['msg']);
        }
    }

    /**
     * 删除指定商品分类
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/5 15:43
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        if (empty($request->id)) {
            return $this->fail('', '请选择要删除的商品分类id');
        }

        //是否存在该指定商品分类
        $checkClass = MaterielClassService::checkClass($request->id);

        if (empty($checkClass)) {
            return $this->fail('', '您要删除的分类不存在，请重试');
        }
        if (!empty($request->type)) {
            $arr[] = $request->id;
        } else {
            $arr = MaterielClassModel::query()
                ->where([
                    'delete_flag' => 0,
                    'parent_id' => $request->id,
                    'main_id' => $this->getMainUserId()
                ])->pluck('id')->toArray();
            $arr[count($arr)] = $request->id;
        }
        DB::beginTransaction();
        try {
            MaterielsTypeModel::query()
                ->whereIn('materiel_class_id', $arr)
                ->update(['delete_flag' => 1]);
            $goodsIdArr = MaterielsTypeModel::query()
                ->whereIn('materiel_class_id', $arr)->pluck('id')->toArray();
            StorageManageModel::query()
                ->whereIn('type_id', $goodsIdArr)->update(['delete_flag' => 1]);
            MaterielProductContentModel::query()
                ->where('product_id', $goodsIdArr)->update(['delete_flag' => 1]);
            MaterielClassModel::query()
                ->whereIn('id', $arr)->update(['delete_flag' => 1]);
            $logData = '分类名称：' . $checkClass['class_name'] . ' 已删除！';
            $this->log('删除物料商品分类', $request->id, $logData);
            DB::commit();
            return $this->success();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->fail('', $e->getMessage());
        }
    }

    /**
     * 编辑商品分类信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/5 17:21
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',
            //type:0->一级分类;1->二级分类
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//页面大小
            'class_name' => 'required',//分类名称
            /* 'class_no' => 'required',//分类编号 */
            'parent_id' => 'required|integer',//上级分类id
        ],
            [
                'id.required' => '分类id标识丢失',
                'id.integer' => '分类id类型错误',
                'type.in' => '类型不合法，请重新选择',
                'class_name.required' => '请输入分类名称',
                /* 'class_no.required' => '请输入分类编号', */
//                'class_no.size' => '编号只能由四位的字母或数字组成',
                'parent_id.required' => '上一级分类id标识丢失',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['parent_id'] = !$data['type'] ? 0 : $data['parent_id'];
        $data['created_at'] = time();
        $data['main_id'] = $this->getMainUserId();
        $logData = '分类名称：' . $data['class_name'] . '信息已修改！';
        $result = MaterielClassService::edit($data);

        switch ($result) {
            case 0:
                return $this->fail('', '目标商品分类不存在，请重试');
            case 1:
                return $this->fail('', '操作的数据不合法，请重试');
            case 2:
                return $this->fail('', '请选择一级商品分类');
            case 3:
                return $this->fail('', '分类编号`' . $data['class_no'] . '`已存在');
            case 4:
                return $this->fail('', '分类`' . $data['class_name'] . '`已存在');
//            case 5:
//                return $this->fail('', '目标商品分类为默认成品库分类，无法修改，请重试');
            default:
                $this->log('修改分类信息', $data, $logData);
                return $this->success();
        }
    }

    //校验物料分类随机code
    public function randNo()
    {
        $data['class_no'] = Util::randStr(4);

        while (!empty(MaterielClassModel::checkMaterielClassCode($data['class_no'], $this->getMainUserId()))) {
            $data['class_no'] = Util::randStr(4);
        }

        return $this->success($data);
    }
}
